import Vue from 'vue'
import Router from 'vue-router'
import routers from './routers'
import store from '@/store'
import iView from 'iview'
import { setToken, getToken, canTurnTo, setTitle } from '@/libs/util'
import config from '@/config'
import { loadMenu } from '@/router/tool'
import { connect, disconnect } from '@/libs/stomp'
const { homeName } = config

Vue.use(Router)

const originalPush = Router.prototype.push

Router.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
let routes = [...routers]
const router = new Router({
  routes: routes,
  mode: 'history'
})
const LOGIN_PAGE_NAME = 'login'

const turnTo = (to, access, next) => {
  if (canTurnTo(to.path, access, routes)) { // 有权限，可访问
    if (to.name === 'error_404' && to.path !== '/error_404') { // 避免刷新问题
      next({ path: to.path })
    }
    if (to.name) { next() } else { next(to) }
  } else next({ replace: true, name: 'error_401' }) // 无权限，重定向到401页面
}

const createRouter = (rs) => new Router({
  routes: rs,
  mode: 'history'
})

const outDo = () => {
  disconnect()
  store.commit('setHasGetRoute', false)
}

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  const token = getToken()
  if (!token && to.name !== LOGIN_PAGE_NAME) {
    outDo()
    next({
      name: LOGIN_PAGE_NAME // 跳转到登录页
    })
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    outDo()
    next() // 跳转
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    // 已登录且要跳转的页面是登录页
    next({
      name: homeName // 跳转到homeName页
    })
  } else {
    if (store.state.user.hasGetRoute) {
      turnTo(to, store.state.user.access, next)
    } else {
      store.dispatch('initRoute').then(res => {
        connect()
        loadMenu(res).then(rt => {
          // 拉取用户信息，通过用户权限和跳转的页面的name来判断是否有权限访问;access必须是一个数组，如：['super_admin'] ['super_admin', 'admin']
          // 这里还有点问题 不想搞了
          let r = createRouter([...routers])
          router.matcher = r.matcher
          router.addRoutes([rt])
          routes = [...routers, rt]
          store.commit('setMenuList', routes)
          store.commit('setHasGetRoute', true)
          turnTo(to, store.state.user.access, next)
        })
      }).catch(() => {
        outDo()
        next({
          name: LOGIN_PAGE_NAME
        })
      })
    }
  }
})

router.afterEach(to => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
